package com.scs.application.modules.base.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.HospitalConfig;
import com.scs.application.modules.base.request.HospitalConfigQueryRequest;
import com.scs.application.modules.base.service.HospitalConfigService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @Description:
 */
@AllArgsConstructor
@RestController
@RequestMapping("/base/hospital_configs")
public class HospitalConfigController extends CrudController<HospitalConfig, String, HospitalConfigService> implements ImAndExAbleController<HospitalConfigQueryRequest> {

    @GetMapping("/page")
    public PageResult page(HospitalConfigQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(HospitalConfigQueryRequest request) {
        List<HospitalConfig> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    @Override
    @PostMapping
    public CommonResult add(@RequestBody @Valid HospitalConfig entity) {
        if (!service.list(Wrappers.<HospitalConfig>query().eq("hospital_id", entity.getHospitalId())).isEmpty()) {
            return CommonResult.error("该医院已存在配置，请勿重复添加");
        }
        return super.add(entity);
    }

    @Override
    @PutMapping
    public CommonResult update(@RequestBody @Valid HospitalConfig entity) {
        if (!service.list(Wrappers.<HospitalConfig>query()
                .eq("hospital_id", entity.getHospitalId())
                .ne("id", entity.getId())).isEmpty()) {
            return CommonResult.error("该医院已存在配置，请勿重复添加");
        }
        return super.update(entity);
    }

    @GetMapping("/getHospitalConfig/{hospitalId}")
    public CommonResult getHospitalConfig(@PathVariable("hospitalId") String hospitalId) {
        HospitalConfig hospitalConfig = null;
        if (StringUtils.isNotBlank(hospitalId)) {
            List<HospitalConfig> hospitalConfigs = service.list(Wrappers.<HospitalConfig>query().eq("hospital_id", hospitalId));
            if (hospitalConfigs != null && hospitalConfigs.size() > 0) {
                hospitalConfig = hospitalConfigs.get(0);
            }
        }
        return CommonResult.ok("获取数据成功", hospitalConfig);
    }

}
